//
// Created by lester on 2023/12/21.
//

#ifndef TEST_TIMESTAMP_H
#define TEST_TIMESTAMP_H
#include <sys/time.h>
class TimeStamp
{
private:
    static const int32_t U_SECONDS = 1000 * 1000;
public:
    int64_t  u_seconds_{};
    explicit TimeStamp(uint64_t u_seconds):u_seconds_(u_seconds){}

    static TimeStamp Now(){
        struct timeval tv{};
        gettimeofday(&tv,nullptr);
        int64_t seconds = tv.tv_sec;
        return TimeStamp(seconds * U_SECONDS + tv.tv_usec);
    }

    std::string Format() const{
        char buf[64] = {0};
        auto seconds = static_cast<time_t>(u_seconds_ / U_SECONDS);
        struct tm tm_time{};
        gmtime_r(&seconds, &tm_time);
        auto microseconds = static_cast<int>(u_seconds_ % U_SECONDS);
        snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d.%06d",
                 tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
                 tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec,
                 microseconds);
        return buf;
    }
};
#endif //TEST_TIMESTAMP_H
